package com.example.demotest.demotest.handler;

import com.example.demotest.demotest.aspect.BigDecimalRange;
import com.example.demotest.demotest.aspect.DateFormatRange;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date;
import java.util.Locale;

/**
 * @author x_weidanlang
 * @version 1.0
 * @date 2022/2/9 15:48
 */

public class DateFormatValidatorHandler   implements ConstraintValidator<DateFormatRange, String> {
    private DateFormatRange dateFormat;

    @Override
    public void initialize(DateFormatRange dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public boolean isValid(String date, ConstraintValidatorContext constraintValidatorContext) {
        String format = dateFormat.format();
        if (format.equals("yyyy-MM-dd HH:mm:ss")) {
            DateTimeFormatter dtf1 = new DateTimeFormatterBuilder()
                    .appendPattern(format)
                    .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                    .toFormatter();
            try {
                LocalDate.parse(date, dtf1);
            } catch (Exception e) {
                return false;
            }
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            try {
                simpleDateFormat.parse(date);
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }


}
